<!-- dataTables -->
<link href="http://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" />
<link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet" />

<!-- page content -->
<div id="moduleDiv" class="right_col" role="main">
    <div class="">
        <div class="page-title">
            <div class="title_left">
                <h3>Resources<small>list</small></h3>
            </div>
        </div>

        <div class="clearfix"></div>

        <div class="row">
            <div class="col-md-12 col-sm-12">
                <div class="x_panel">
                    <div class="x_title">
                        <button
                                class="btn btn-primary"
                                type="button"
                                data-toggle="modal"
                                data-target="#modalAdd"
                                @click="initModuleAdd()"
                        >
                            新增
                        </button>
                        <ul class="nav navbar-right panel_toolbox">
                            <li>
                                <a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                            </li>
                            <li class="dropdown">
                                <a
                                        href="#"
                                        class="dropdown-toggle"
                                        data-toggle="dropdown"
                                        role="button"
                                        aria-expanded="false"
                                ><i class="fa fa-wrench"></i
                                ></a>
                                <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                    <a class="dropdown-item" href="#">Settings 1</a>
                                    <a class="dropdown-item" href="#">Settings 2</a>
                                </div>
                            </li>
                            <li>
                                <a class="close-link"><i class="fa fa-close"></i></a>
                            </li>
                        </ul>
                        <div class="clearfix"></div>
                    </div>
                    <div class="x_content">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="card-box table-responsive">
                                    <table
                                            id="moduleTable"
                                            class="table table-striped table-bordered"
                                            style="width: 100%"
                                    >
                                        <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Permission</th>
                                            <th>Create Date</th>
                                            <th>Operation</th>
                                        </tr>
                                        </thead>

                                        <tbody></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 加入新增碎片页面 -->
    <div th:replace="account/resourceAdd"></div>
    <div th:replace="account/resourceEdit"></div>
</div>

<!-- Datatables -->
<script src="/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>

<script>
    new Vue({
        el: "#moduleDiv",
        data: {
            // 表格数据结构
            tableData: {
                draw: 0,
                recordsTotal: 0,
                recordsFiltered: 0,
                data: [],
            },
            model: {
                id: "",
                permission: "",
                createDate: "",
                roles: [],
            },
            pageSize: 5,
            allRoles: [],
            dataTable: "",
        },
        methods: {
            // 行数据结构
            rowData: function (id, permission, createDate) {
                var module = {};
                module.id = id;
                module.permission = permission;
                module.createDate = createDate;
                module.operate = function () {
                    return (
                        "<a href='#' class='btn_editcolor' data-toggle='modal' data-target='#modalEdit' " +
                        "onclick='initEditModule(\"" +
                        id +
                        "\")'>编辑</a>&nbsp;" +
                        "<a href='javascript:void(0);' onclick='deleteModule(\"" +
                        id +
                        "\")' class='btn_editcolor'>删除</a>"
                    );
                };
                return module;
            },
            // 初始化表格数据
            initTableData: function () {
                var self = this;

                this.dataTable = $("#moduleTable").DataTable({
                    paging: true, //分页
                    serverSide: true, //开启后端分页
                    pagingType: "full_numbers", //分页样式的类型simple/simple_numbers/full/full_numbers
                    pageLength: self.pageSize, //定义初始的页长
                    processing: true,
                    destroy: true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
                    lengthChange: true, //控制是否能够调整每页的条数
                    searching: true,
                    "data-show-refresh": true,
                    ordering: true,
                    autoWidth: false,
                    ajax: function (data, callback, settings) {
                        // 从data获取查询数据
                        var columIndex = data.order[0].column;
                        var direction = data.order[0].dir;
                        var sort = data.columns[columIndex].name;
                        pageSize = data.length == undefined ? pageSize : data.length;

                        var search = {};
                        search.currentPage = data.start / pageSize + 1;
                        search.pageSize = pageSize;
                        search.sort = sort;
                        search.direction = direction;
                        search.keyword = data.search.value;

                        $.ajax({
                            url: "/api/resourceList",
                            type: "post",
                            contentType: "application/json",
                            data: JSON.stringify(search),
                            success: function (rs) {
                                // 拿到结果集做判断
                                if (!rs) {
                                    layer.alert("请求出错，请稍后重试" + rs.errmsg, { icon: 2 });
                                    callback(self.tableData);
                                    return;
                                }
                                if (rs.list == null) {
                                    $("#moduleTable tbody tr").remove();
                                    $("#loading").remove();
                                    callback(self.tableData);
                                    return;
                                }

                                $("#loading").remove();

                                // 封装数据
                                var rowsData = [];
                                for (var i = 0; i < rs.list.length; i++) {
                                    //包装行数据
                                    var rowData = self.rowData(
                                        rs.list[i].id,
                                        rs.list[i].permission,
                                        rs.list[i].createDate
                                    );

                                    // 将行数据放到数组里
                                    rowsData.push(rowData);
                                }
                                self.tableData.data = rowsData;
                                self.tableData.recordsTotal = rs.total;
                                self.tableData.recordsFiltered = rs.total;
                                callback(self.tableData);
                            },
                            error: function (data) {
                                layer.alert(data.responseText, { icon: 0 });
                            },
                        });
                    },
                    columns: [
                        //定义行数据字段
                        { data: "id", name: "id", sortable: true },
                        { data: "permission", name: "permission", sortable: true },
                        { data: "createDate", name: "create_date", sortable: true },
                        { data: "operate", width: "80px", sortable: false },
                    ],
                });
            },
            // 初始化新增面板
            initModuleAdd: function () {
                this.model = {
                    id: "",
                    permission: "",
                    createDate: "",
                    roles: [],
                };
            },
            // 初始化所有角色列表
            initAllRoles: function () {
                var self = this;
                $.ajax({
                    url: "/api/roles",
                    type: "get",
                    success: function (result) {
                        self.allRoles = result;
                    },
                    error: function (error) {
                        layer.alert(error.responseText, { icon: 0 });
                    },
                });
            },
            // 新增模型
            addModule: function () {
                // 包装并赋值
                this.model.roles = this.model.roles.map((item) => {
                    var role = {};
                    role.id = item;
                    return role;
                });

                var self = this;
                $.ajax({
                    url: "/api/resource",
                    type: "post",
                    contentType: "application/json",
                    data: JSON.stringify(self.model),
                    success: function (result) {
                        if (result.status != 200) {
                            layer.alert(result.message, { icon: 0 });
                        } else {
                            $("#modalAdd").modal("hide");
                            self.initTableData();
                        }
                    },
                    error: function (error) {
                        layer.alert(error.responseText, { icon: 0 });
                    },
                });
            },
            initEditModule: function (id) {
                var self = this;
                $.ajax({
                    url: "/api/resource/" + id,
                    type: "get",
                    success: function (result) {
                        result.roles = result.roles.map((item) => {
                            return item.id;
                        });
                        self.model = result;
                    },
                    error: function (error) {
                        layer.alert(error.responseText, { icon: 0 });
                    },
                });
            },
            editModule: function () {
                // 包装并赋值
                this.model.roles = this.model.roles.map((item) => {
                    var role = {};
                    role.id = item;
                    return role;
                });

                var self = this;
                $.ajax({
                    url: "/api/resource",
                    type: "put",
                    contentType: "application/json",
                    data: JSON.stringify(self.model),
                    success: function (result) {
                        if (result.status != 200) {
                            layer.alert(result.message, { icon: 0 });
                        } else {
                            $("#modalEdit").modal("hide");
                            // self.initTableData();
                            self.dataTable.draw(false);
                        }
                    },
                    error: function (error) {
                        layer.alert(error.responseText, { icon: 0 });
                    },
                });
            },
            deleteModule: function (id) {
                var self = this;
                bootbox.confirm("Are you sure?", function (result) {
                    if (result) {
                        $.ajax({
                            url: "/api/resource/" + id,
                            type: "delete",
                            success: function (result) {
                                if (result.status != 200) {
                                    layer.alert(result.message, { icon: 0 });
                                } else {
                                    $("#modalEdit").modal("hide");
                                    self.initTableData();
                                }
                            },
                            error: function (error) {
                                layer.alert(error.responseText, { icon: 0 });
                            },
                        });
                    }
                });
            },
        },
        created() {
            window.initEditModule = this.initEditModule;
            window.deleteModule = this.deleteModule;
        },
        mounted() {
            this.initTableData();
            this.initAllRoles();
        },
    });
</script>